package com.mallcai.bigdata.ladon.dpl.mapper.peekdata.provider;

import com.mallcai.bigdata.ladon.dpl.entity.peekdata.Model;
import com.mallcai.bigdata.ladon.dpl.mapper.BaseSqlProvider;
import com.mallcai.bigdata.ladon.dpl.mapper.system.UserMapper;
import com.mallcai.bigdata.ladon.dpl.mapper.system.provider.UserSqlProvider;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author gst
 * @date 2019-12-30 20:36
 */
public class ModelSqlProvider extends BaseSqlProvider<Model> {

    public static final String TB_MODEL = "pd_model";

    @Override
    public String getTableName() {
        return TB_MODEL;
    }

    @Override
    public Map<String, String> getInsertColumns() {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("datasource_id", "#{datasourceId}");
        map.put("name", "#{name}");
        map.put("table_name", "#{tableName}");
        map.put("`desc`", "#{desc}");
        map.put("status", "0");
        return map;
    }

    @Override
    public Map<String, String> getUpdateColumns() {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("datasourceId", "datasource_id");
        map.put("name", "name");
        map.put("tableName", "table_name");
        map.put("desc", "`desc`");
        map.put("status", "status");
        return map;
    }

    /**
     * 根据参数查询
     */
    public String getByParams(Map<String, Object> map) {
        Map<String, Object> params = getParams(map);

        StringBuilder sb = new StringBuilder();
        sb.append("tb_m.archive = 0");
        if (params.containsKey("name") && StringUtils.isNotBlank(params.get("name").toString())) {
            sb.append(" and tb_m.name LIKE concat('%',#{params.name},'%')");
        }
        if (params.containsKey("tableName") && StringUtils.isNotBlank(params.get("tableName").toString())) {
            sb.append(" and tb_m.table_name = #{params.tableName}");
        }
        if (params.containsKey("status")) {
            sb.append(" and tb_m.status = #{params.status}");
        }
        return new SQL() {
            {
                SELECT("tb_m.*, tb_u.nickname AS creator");
                FROM(TB_MODEL + " tb_m");
                LEFT_OUTER_JOIN(UserSqlProvider.TB_USER + " tb_u ON tb_u.id = tb_m.created_by ");
                WHERE(sb.toString());
            }
        }.toString();
    }
}
